import { memo, useEffect, useState } from "react";
import { ModificationWrapper, PatientWrapper } from "./style";
import { useAppDispatch, useAppSelector } from "../../../store";
import {
  fetchDeptListAction,
  fetchDoctorListAction,
  fetchExaminationListAction,
  fetchGetPatientDetailInfoAction,
  fetchGetTaskExaminationAction,
  fetchGetTaskListAction,
  fetchIllnessListAction,
  fetchModifyPatientInforAction,
  fetchNurseListAction,
  fetchPatientsUserInfoAction,
} from "../../../store/modules/patient";
import {
  SearchOutlined,
  SyncOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { IconSearch, IconRefresh } from "@arco-design/web-react/icon";
import {
  Input,
  Form,
  AutoComplete,
  Select,
  Button,
  Tooltip,
  Space,
  DatePicker,
} from "antd";
import {
  Table,
  Message,
  Modal,
  Divider,
  Card,
  Tag,
  Notification,
  Button as AraoButton,
} from "@arco-design/web-react";
import CheckModification from "./CheckModification";
import TaskModification from "./TaskModification";
import Detail from "./Detail";
import CheckTaskDetail from "./CheckTaskDetail";
import dayjs from "dayjs";
import { useForm } from "antd/es/form/Form";
import { deletePatientInfo } from "../../../service/modules/patient";

interface IUserInfor {
  avatar?: string;
  createBy: string | null;
  createTime: string | null;
  deptId?: number;
  dischargeDate?: string;
  doctorId?: number;
  email?: string;
  familyHistory?: string;
  hospitalId?: number;
  hospitalizationDate?: string;
  id: number;
  illnessId?: number;
  image?: string;
  medicalRecord?: string;
  name?: string;
  nickName?: string;
  nurseId?: number;
  operation?: string;
  operationDate?: string;
  pastMedicalHistory?: string;
  programmeTitle: string | null;
  phonenumber?: string;
  programmeId?: number;
  sex?: string;
  remark: null;
  updateBy: null;
  state?: string;
  userId: number;
  username?: string;
  updateTime?: string | null;
}

const PatientPage = () => {
  const dispatch = useAppDispatch();
  const [searchForm] = Form.useForm();
  const [userInfoForm] = useForm();

  const [visible, setVisible] = useState(false);
  const [PatientId, setPatientId] = useState(0);
  //*搜索重置
  const [isSearchClicked, setIsSearchClicked] = useState(false);
  const [isRotating, setIsRotating] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [isDisplay, setIsDisplay] = useState(false);
  // 分页数据查询
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  //表单选项
  const [searchParams, setSearchParams] = useState<{
    patientName?: string;
    doctorName?: string;
    nurseName?: string;
    operationName?: string;
  }>({});
  const {
    patientDetailInfo,
    patientUsersInfo,
    doctorList,
    nurseList,
    deptList,
    illnessList,
    total,
  } = useAppSelector((state) => state.patient);

  const limitPatientNum = {
    pageNum: pageNum,
    pageSize: pageSize,
  };

  const [userInfor, setUserInfor] = useState<IUserInfor>({
    avatar: patientDetailInfo?.avatar,
    createBy: patientDetailInfo?.createBy,
    createTime: patientDetailInfo?.createTime,
    deptId: patientDetailInfo?.deptId,
    dischargeDate: patientDetailInfo?.dischargeDate,
    doctorId: patientDetailInfo?.doctorId,
    email: patientDetailInfo?.email,
    familyHistory: patientDetailInfo?.familyHistory,
    hospitalId: patientDetailInfo?.hospitalId,
    hospitalizationDate: patientDetailInfo?.hospitalizationDate,
    id: patientDetailInfo?.id,
    illnessId: patientDetailInfo?.illnessId,
    image: patientDetailInfo?.image,
    medicalRecord: patientDetailInfo?.medicalRecord,
    name: patientDetailInfo?.name,
    nickName: patientDetailInfo?.nickName,
    nurseId: patientDetailInfo?.nurseId,
    operation: patientDetailInfo?.operation,
    operationDate: patientDetailInfo?.operationDate,
    pastMedicalHistory: patientDetailInfo?.pastMedicalHistory,
    phonenumber: patientDetailInfo?.phonenumber,
    programmeId: patientDetailInfo?.programmeId,
    programmeTitle: patientDetailInfo?.programmeTitle,
    remark: patientDetailInfo?.remark,
    sex: patientDetailInfo?.sex,
    state: patientDetailInfo?.state,
    updateBy: patientDetailInfo?.updateBy,
    updateTime: patientDetailInfo?.updateTime,
    userId: patientDetailInfo?.userId,
    //   username: userdetailinfor.username
  });

  useEffect(() => {
    dispatch(fetchDoctorListAction({ deptId: "", doctorId: "", nurseId: "" }));
    dispatch(fetchNurseListAction({ deptId: "", doctorId: "", nurseId: "" }));
    dispatch(fetchDeptListAction());
    dispatch(fetchIllnessListAction());
    dispatch(fetchExaminationListAction());
    dispatch(fetchGetTaskListAction());
    dispatch(fetchPatientsUserInfoAction(limitPatientNum));
  }, [dispatch]);
  // console.log(patientUsersInfo);

  /**
   *@初始化病人修改form
   */

  useEffect(() => {
    if (patientDetailInfo && Object.keys(patientDetailInfo).length > 0) {
      userInfoForm.setFieldsValue({
        userId: patientDetailInfo.userId,
        name: patientDetailInfo.name,
        doctorId: patientDetailInfo.doctorId,
        nurseId: patientDetailInfo.nurseId,
        illnessId: patientDetailInfo.illnessId,
        operation: patientDetailInfo.operation,
        operationDate: patientDetailInfo.operationDate
          ? dayjs(patientDetailInfo.operationDate)
          : null,
        medicalRecord: patientDetailInfo.medicalRecord || "无既往病史",
      });
    }
  }, [userInfoForm, patientDetailInfo]);
  // console.log(dayjs(patientDetailInfo.operationDate).format("YYYY年MM月DD日"));
  //?提交病人修改信息
  const onFinish = async (values: IUserInfor) => {
    // console.log(values);
    try {
      const formattedOperationDate = values.operationDate
        ? dayjs(values.operationDate).format("YYYY-MM-DD")
        : null;
      // console.log(formattedOperationDate);

      const payload = {
        ...patientDetailInfo,
        ...values,
        operationDate: formattedOperationDate,
        doctorId: Number(values.doctorId),
        nurseId: Number(values.nurseId),
        illnessId: Number(values.illnessId),
        userId: Number(PatientId),
      };
      console.log(payload);

      await dispatch(fetchModifyPatientInforAction(payload)).unwrap();

      await Promise.all([
        dispatch(fetchPatientsUserInfoAction(limitPatientNum)).unwrap(),
        dispatch(fetchGetPatientDetailInfoAction(PatientId)).unwrap(),
      ]);
    } catch (error) {
      Message.error("修改失败，请重试");
      console.error("修改病人信息失败:", error);
    }
  };
  //*删除病人信息
  const [isDelete, setIsDelete] = useState(false);
  const removePatient = () => {
    if (selectedRowKeys.length === 0) {
      Message.warning("请选择要删除的项");
      return;
    }
    const id = `${Date.now()}`;
    Notification.info({
      id,
      content: "你确定要删除这个用户信息吗",
      title: "警告",
      btn: (
        <span>
          <Button
            onClick={() => {
              setIsDelete(false);
              Notification.remove(id);
              setSelectedRowKeys([]);
            }}
          >
            取消
          </Button>
          <Button
            onClick={() => {
              Notification.remove(id);
              setIsDelete(true);
              if (isDelete) {
                deletePatientInfo(PatientId);
              }
              setIsDelete(false);
            }}
          >
            确认
          </Button>
        </span>
      ),
    });
  };
  /**
   * @搜索过滤相关事件操作
   */

  //*按钮重置搜索
  const handleSearchClick = () => {
    setIsSearchClicked(true);
    if (isSearchClicked) return;
    else {
      setIsSearchClicked(true);
      setTimeout(() => setIsSearchClicked(false), 500);
    }
  };
  const onReset = () => {
    if (isRotating) return;
    else {
      setIsRotating(true);
      setTimeout(() => {
        setIsRotating(false);
      }, 300);
    }
    searchForm.resetFields();
    setSearchParams({});
  };
  //?过滤提交事件
  const onFinishSearch = (values: {
    doctorName?: string;
    nurseName?: string;
    patientName?: string;
    operationName?: string;
  }) => {
    setSearchParams(values);
  };
  // console.log(searchParams);
  /**
   * @病人列表解决为null值
   */
  const patientOptions = patientUsersInfo?.map((item, index) => {
    return {
      value: item.name || `未知用户${patientUsersInfo[index]?.userId}`,
      key: item.userId,
    };
  });

  /**
   * @点击检查任务按钮获得对应的检查任务数据操作
   */
  const handlePatientExaminationandTask = (params: { userId: number }) => {
    dispatch(fetchGetTaskExaminationAction(params));
  };
  /**
   * @获取病人详细信息
   */
  const handlePatientDetailInfo = async (userId: number) => {
    await dispatch(fetchGetPatientDetailInfoAction(userId as number));
  };

  /**
   * @表单
   */

  const colums = [
    { title: "用户id", dataIndex: "patientId" },
    { title: "用户姓名", dataIndex: "patientName" },
    { title: "科室名字", dataIndex: "deptName" },
    { title: "医院名称", dataIndex: "hospitalName" },
    { title: "医生名称", dataIndex: "doctorName" },
    { title: "护士名称", dataIndex: "nurseName" },
    { title: "病种名称", dataIndex: "illnessName" },
    { title: "治疗方案", dataIndex: "programmeTitle" },
    { title: "手术名称", dataIndex: "operationName" },
    { title: "住院日期", dataIndex: "createTime" },
    {
      title: "操作",
      dataIndex: "management",
      render: (_: any, record: any) => {
        const userId = record.key;
        return (
          <Space size="small" direction="vertical" align="center">
            <CheckModification
              userId={userId}
              getDataFn={handlePatientExaminationandTask}
            />
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <TaskModification
                userId={userId}
                getDataFn={handlePatientExaminationandTask}
              />
              <Detail userId={userId} getDetailInfo={handlePatientDetailInfo} />
            </div>

            <CheckTaskDetail userId={userId as number} />
            <div style={{ display: "flex" }}>
              <Button
                type="link"
                size="small"
                style={{ gap: "2px", width: "56px", height: "22px" }}
                icon={<EditOutlined />}
                onClick={() => {
                  if (selectedRowKeys.length === 0) {
                    Message.warning("请选择要修改的项");
                    return;
                  }
                  setVisible(true);
                  setPatientId(userId);
                  handlePatientDetailInfo(userId);
                }}
              >
                修改
              </Button>
              <Button
                type="link"
                size="small"
                style={{ gap: "2px", width: "56px", height: "22px" }}
                icon={<DeleteOutlined />}
                onClick={removePatient}
              >
                删除
              </Button>
            </div>
          </Space>
        );
      },
    },
  ];
  const dataSource = patientUsersInfo?.map((item, index) => {
    const currentPatientInfo = patientUsersInfo[index];
    // console.log(currentPatientInfo);
    const matchDeptName = currentPatientInfo?.deptId
      ? deptList.find((dept) => dept.deptId === currentPatientInfo.deptId)
      : undefined;
    const matchDoctorName = currentPatientInfo?.doctorId
      ? doctorList.find((item) => item.userId === currentPatientInfo.doctorId)
      : undefined;
    const matchHospName = currentPatientInfo?.deptId
      ? deptList.find((id) => id.deptId === currentPatientInfo.hospitalId)
      : undefined;
    const matchNurseName = currentPatientInfo?.nurseId
      ? nurseList.find((id) => id.userId === currentPatientInfo.nurseId)
      : undefined;
    const matchIllnessName = currentPatientInfo?.illnessId
      ? illnessList.find((item) => item.id === currentPatientInfo.illnessId)
      : undefined;
    return {
      key: item?.userId,
      patientId: item?.userId,
      patientName: item.name || `未知用户${item?.userId}`,
      deptName: matchDeptName?.deptName || "未知科室",
      hospitalName: matchHospName?.deptName || "未知医院",
      doctorName: matchDoctorName?.nickName || "未知医生",
      nurseName: matchNurseName?.nickName || "未知护士",
      illnessName: matchIllnessName?.name || "未知病种",
      programmeTitle: item?.programmeTitle || "",
      operationName: item?.operation || "",
      createTime: item?.hospitalizationDate || "",
    };
  });

  // 过滤表单数据
  const filterDataSource = dataSource?.filter((item) => {
    if (Object.keys(searchParams).length === 0) return dataSource;
    const matchDoctorName =
      !searchParams.doctorName ||
      item?.doctorName?.includes(searchParams.doctorName); // 改为 includes
    const matchNurseName =
      !searchParams.nurseName ||
      item?.nurseName?.includes(searchParams.nurseName); // 改为 includes
    const matchPatientName =
      !searchParams.patientName ||
      item.patientName.includes(searchParams.patientName);
    const matchOperationName =
      !searchParams.operationName ||
      item.operationName.includes(searchParams.operationName);
    return (
      matchNurseName &&
      matchDoctorName &&
      matchPatientName &&
      matchOperationName
    );
  });

  //?表单选择框
  const onSelectChange = (newSelectedRowKeys: any[]) => {
    // console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <PatientWrapper>
      <ModificationWrapper>
        <Modal
          title="修改病人信息"
          visible={visible}
          cancelText="取消"
          onOk={async () => {
            try {
              await userInfoForm.submit();
              Message.success("修改成功");
              setSelectedRowKeys([]);
              setVisible(false);
            } catch (error) {
              // 表单验证失败，不执行提交
              console.log("表单验证失败:", error);
            }
          }}
          onCancel={() => setVisible(false)}
          autoFocus={false}
          focusLock={true}
        >
          <Card bordered={false}>
            <Form
              form={userInfoForm}
              labelCol={{ span: 7 }}
              wrapperCol={{ span: 13 }}
              onFinish={onFinish}
              // onValuesChange={onFinish}
            >
              <div style={{ height: "100px" }}>
                <h3 className="section-title">
                  <span>👤</span>
                  基本信息
                </h3>
                <div style={{ position: "relative", height: "20px" }}>
                  <Tag
                    color="blue"
                    style={{
                      position: "absolute",
                      left: "0px",
                      width: "120px",
                      top: "20px",
                      textAlign: "center",
                      height: "30px",
                      fontSize: "15px",
                    }}
                  >
                    用户Id: {PatientId}
                  </Tag>
                  <Tag
                    color="blue"
                    style={{
                      height: "30px",
                      fontSize: "15px",
                      textAlign: "center",
                      position: "absolute",
                      right: 0,
                      top: "20px",
                      width: "120px",
                    }}
                  >
                    用户姓名:{patientDetailInfo?.name}
                  </Tag>
                </div>
              </div>

              <Form.Item
                label="用户姓名"
                name="name"
                rules={[{ required: true, message: "请输入用户姓名" }]}
              >
                <Input
                  placeholder="修改用户姓名"
                  style={{ backgroundColor: "lightgrey" }}
                />
              </Form.Item>

              <Divider />

              <div className="formBox">
                <h3 className="section-title">
                  <span className="title-icon">🏥</span>
                  医疗信息
                </h3>
                <div className="form-row">
                  <Form.Item
                    label="主治医生"
                    name="doctorId"
                    rules={[{ required: true, message: "请选择主治医生" }]}
                  >
                    <Select
                      placeholder="请选择主治医生"
                      suffixIcon={<span className="select-icon">👨‍⚕️</span>}
                    >
                      {doctorList?.map((item) => (
                        <Select.Option
                          key={item.userId}
                          value={item.userId}
                          label={item.nickName}
                        >
                          <span>👨‍⚕️</span>
                          {item.nickName}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item label="责任护士" name="nurseId">
                    <Select
                      style={{ backgroundColor: "lightgrey" }}
                      placeholder="请选择责任护士"
                      showSearch
                      optionFilterProp="children"
                      suffixIcon={<span className="select-icon">👩‍⚕️</span>}
                    >
                      {nurseList?.map((item) => (
                        <Select.Option key={item.userId} value={item.userId}>
                          <div className="option-item">
                            <span className="option-icon">👩‍⚕️</span>
                            {item.nickName}
                          </div>
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                </div>

                <Form.Item label="病种名称" name="illnessId">
                  <Select
                    style={{ backgroundColor: "lightgrey" }}
                    placeholder="请选择病种"
                    suffixIcon={<span className="select-icon">🩺</span>}
                  >
                    {illnessList?.map((item) => (
                      <Select.Option key={item.id} value={item.id}>
                        <div>
                          <span>🩺</span>
                          {item.name}
                        </div>
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </div>

              <Divider />

              <div>
                <h3>
                  <span>🔪</span>
                  手术信息
                </h3>
                <div>
                  <Form.Item label="手术名称" name="operation">
                    <Input
                      placeholder="请输入手术名称"
                      style={{ backgroundColor: "lightgrey" }}
                    />
                  </Form.Item>

                  <Form.Item label="手术时间" name="operationDate">
                    <DatePicker
                      // value={dayjs(patientDetailInfo.operationDate).format(
                      //   "YYYY年MM月DD日"
                      // )}
                      onChange={(_, dateString) => {
                        // console.log(dateString);
                        setUserInfor({
                          ...userInfor,
                          operationDate: dateString as string,
                        });
                      }}
                      // suffixIcon={<span className="date-icon">📅</span>}
                    />
                  </Form.Item>
                </div>
              </div>

              <Divider className="section-divider" />

              <div className="form-section">
                <h3 className="section-title">
                  <span className="title-icon">📋</span>
                  病历信息
                </h3>
                <Form.Item label="病历记录" name="medicalRecord">
                  <Input.TextArea
                    rows={4}
                    placeholder="请输入病历记录"
                    // showCount
                    maxLength={500}
                  />
                </Form.Item>
              </div>
            </Form>
          </Card>
        </Modal>
      </ModificationWrapper>

      <div className={isDisplay ? "disSearchForm" : "searchForm"}>
        <Form form={searchForm} layout="inline" onFinish={onFinishSearch}>
          <div className="searchItems">
            <Form.Item label="用户姓名" name="patientName">
              <AutoComplete
                options={patientOptions}
                placeholder="请输入用户姓名"
                allowClear
                style={{ width: "150px", height: "30px", userSelect: "none" }}
              />
            </Form.Item>
          </div>
          <div className="searchItems">
            <Form.Item label="医生姓名" name="doctorName">
              <Select
                allowClear
                placeholder="请选择医生"
                className="custom-select"
                style={{ width: "150px", height: "30px", userSelect: "none" }}
              >
                {doctorList &&
                  doctorList.map((item) => {
                    return (
                      <Select.Option key={item.userId} value={item.nickName}>
                        {item.nickName}
                      </Select.Option>
                    );
                  })}
              </Select>
            </Form.Item>
          </div>
          <div className="searchItems">
            <Form.Item label="护士姓名" name="nurseName">
              <Select
                allowClear
                placeholder="请选择护士"
                className="custom-select"
                style={{ width: "150px", height: "30px", userSelect: "none" }}
              >
                {nurseList &&
                  nurseList?.map((item) => {
                    return (
                      <Select.Option key={item.userId} value={item.nickName}>
                        {item.nickName}
                      </Select.Option>
                    );
                  })}
              </Select>
            </Form.Item>
          </div>
          <div className="searchItems">
            <Form.Item label="手术名称" name="operationName">
              <AutoComplete
                placeholder="请输入手术名称"
                allowClear
                style={{ width: "150px", height: "30px", userSelect: "none" }}
              />
            </Form.Item>
          </div>
          <div className="searchItems">
            <Button
              type="primary"
              icon={
                <SearchOutlined
                  className={
                    isSearchClicked
                      ? "search-icon-enlarge"
                      : "dissearch-icon-enlarge"
                  }
                />
              }
              onClick={handleSearchClick}
              htmlType="submit"
            >
              搜索
            </Button>
          </div>
          <div className="searchItems">
            <Button
              type="primary"
              icon={
                <SyncOutlined
                  className={isRotating ? "reset-icon-rotate" : ""}
                />
              }
              onClick={onReset}
            >
              重置
            </Button>
          </div>
        </Form>
      </div>
      <div className="patientCenterBtn">
        <div className="btnItems">
          <div className="btnItem">
            <AraoButton
              status="warning"
              icon={<EditOutlined />}
              disabled={selectedRowKeys.length < 1}
              onClick={() => {
                setVisible(true);
                setPatientId(PatientId);
                handlePatientDetailInfo(PatientId);
              }}
            >
              修改
            </AraoButton>
          </div>
          <div className="btnItem">
            <AraoButton
              status="danger"
              disabled={selectedRowKeys.length < 1}
              icon={<DeleteOutlined />}
              onClick={removePatient}
            >
              删除
            </AraoButton>
          </div>
        </div>
        <div className="iconItems">
          <div style={{ margin: "5px" }}>
            <Tooltip title="隐藏搜索">
              <Button
                onClick={() => {
                  setIsDisplay(!isDisplay);
                }}
                icon={<IconSearch />}
                style={{ borderRadius: "50%", padding: "16px" }}
              />
            </Tooltip>
          </div>
          <div style={{ margin: "5px" }}>
            <Tooltip title="刷新">
              <Button
                onClick={() => {
                  Message.success("表单已刷新");
                  onReset();
                }}
                icon={<IconRefresh />}
                style={{ borderRadius: "50%", padding: "16px" }}
              />
            </Tooltip>
          </div>
        </div>
      </div>
      <div className="patientTable">
        <Table
          columns={colums}
          data={filterDataSource}
          rowSelection={rowSelection}
          style={{ userSelect: "none" }}
          pagination={{
            total: total,
            pageSize: 10,
            sizeOptions: [10, 20, 30, 40], // 可选的每页条数
            showJumper: true, // 显示"跳转至"输入框（Arco 特有）
            showTotal: (total) => `共 ${total} 条`, // 自定义总条数文案
            sizeCanChange: true, // 允许动态调整每页条数（Arco 特有）
            hideOnSinglePage: false,
            onChange: (current, pageSize) => {
              // console.log("当前页：", current, "每页条数：", pageSize);
              setPageNum(current);
              setPageSize(pageSize);
            },
            style: { marginRight: "15px" },
          }}
        ></Table>
      </div>
    </PatientWrapper>
  );
};
export default memo(PatientPage);
